import { request } from "./request";
import type { RequestMethod } from "./types";

export interface SafeRequestResponse<T> {
  data: T | undefined;
  message?: string;
}

type SafeRequest = (<T = any>(
  url?: string,
  method?: RequestMethod,
  data?: any,
  options?: any
) => Promise<SafeRequestResponse<T>>) &
  Record<
    Lowercase<RequestMethod>,
    <T = any>(
      url: string,
      data?: any,
      options?: any
    ) => Promise<SafeRequestResponse<T>>
  >;

export const safe_request = (async (
  url: string,
  method: RequestMethod,
  data?: any,
  options?: any
) => {
  let response: any;
  try {
    response = await request(url, method, data, options);

    return response.data;
  } catch (error) {}
}) as SafeRequest;

safe_request.get = (url, data, options) =>
  safe_request(url, "GET", data, options);

safe_request.post = (url, data, options) =>
  safe_request(url, "POST", data, options);

safe_request.delete = (url, data, options) =>
  safe_request(url, "DELETE", data, options);

safe_request.patch = (url, data, options) =>
  safe_request(url, "PATCH", data, options);
